<?php

namespace App\Models;

/**
 * App\Models\SystemConfig
 *
 * @method static \Illuminate\Database\Eloquent\Builder|SystemConfig newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|SystemConfig newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|SystemConfig query()
 * @mixin \Eloquent
 * @property int $id
 * @property int $type
 * @property string $config
 * @property \Illuminate\Support\Carbon $updated_at
 * @property \Illuminate\Support\Carbon $created_at
 * @method static \Illuminate\Database\Eloquent\Builder|SystemConfig whereConfig($value)
 * @method static \Illuminate\Database\Eloquent\Builder|SystemConfig whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|SystemConfig whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|SystemConfig whereType($value)
 * @method static \Illuminate\Database\Eloquent\Builder|SystemConfig whereUpdatedAt($value)
 */
class SystemConfig extends BaseModel
{
    protected $table = 'system_config';
    protected $casts = [
        'config' => 'json'
    ];
    private static $configBag = [];


    /**
     * 类型
     * @param $query
     * @param $type
     * @return mixed
     */
    public function scopeType($query, $type)
    {
        return $query->where('type', $type);
    }

    /**
     * 通过type获取配置信息
     * @param $type
     */
    public static function getByType($type)
    {
        $result = [];

        if (!$type) {
            return false;
        }

        if (isset(self::$configBag[$type])) {
            return self::$configBag[$type];
        } else {
            $config = self::type($type)->first();

            if ($config) {
                $result = self::$configBag[$type] = $config->config;
            }
        }

        return $result;
    }

    /**
     * 获取type模型
     * @param $type
     */
    public static function getModelByType($type)
    {
        $result = null;

        if (!$type) {
            return $result;
        }

        $result = self::type($type)->first();
        if (!$result) {
            $result = new self();
        }
        return $result;
    }
}
